﻿using System;
using System.Globalization;
using System.Text;
using YAWD.Utils;
using System.Collections.Generic;
using YAWD.Properties;

namespace YAWD.BL.Providers
{
    public class Bing : IProvider
    {
        public string URL { get; set; }
        public string Path { get; set; }
        public string FirstImage { get; set; }
        public string LastDwImage { get; set; }
        public DateTime LastUpdated { get; set; }
        public string LastId { get; set; }

        private bool _isCancelationPending;
        private double _current;
        private string _currentImage = string.Empty;
        private IList<string> _images;

        public double Current
        {
            get { return this._current; }
            set
            {
                this._current = value;
                OnProgressChanged(EventArgs.Empty);
            }
        }

        public string CurrentImage
        {
            get { return this._currentImage; }
            set
            {
                this._currentImage = value;
                OnCurrentImageChanged(EventArgs.Empty);
            }
        }

        public IList<string> Images
        {
            get { return this._images; }
            set
            {
                this._images = value;
                OnImagesChanged(EventArgs.Empty);
            }
        }

        public event EventHandler ProgressChanged;
        public event EventHandler CurrentImageChanged;
        public event EventHandler ImagesChanged;

        public IProvider Init()
        {
            return Util.ReadProviderSettings(this);
        }

        protected virtual void OnProgressChanged(EventArgs e)
        {
            if (this.ProgressChanged != null)
                this.ProgressChanged(this, e);
        }
        protected virtual void OnCurrentImageChanged(EventArgs e)
        {
            if (this.CurrentImageChanged != null)
                this.CurrentImageChanged(this, e);
        }
        protected virtual void OnImagesChanged(EventArgs e)
        {
            if (this.ImagesChanged != null)
                this.ImagesChanged(this, e);
        }
        public int getAll()
        {
            DateTime start;
            CultureInfo us = CultureInfo.GetCultureInfo("en-US");

            if (DateTime.TryParseExact(FirstImage, "yyyyMMdd", us, DateTimeStyles.None, out start) == true)
                return getImages(start);
            else
                return 0;
        }

        private int getImages(DateTime start)
        {
            this._isCancelationPending = false;

            int downloadedImage = 0;
            DateTime end = DateTime.Now;
            string month = string.Empty;
            string year = string.Empty;
            string webPage = string.Empty;
            CultureInfo us = CultureInfo.GetCultureInfo("en-US");

            TimeSpan nbrItems = end - start;
            double interleave = (double)100 / nbrItems.TotalDays;

            Settings settings = Settings.Default;
            string initPath;
            if (string.IsNullOrWhiteSpace(settings.WallPapersPath))
                initPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            else
                initPath = settings.WallPapersPath;


            for (DateTime i = start; i < end; i = i.AddDays(1))
            {
                //exit if the user cancels
                if (this._isCancelationPending == true)
                {
                    this.LastUpdated = DateTime.Now;
                    Util.SaveToConfigFile("LastUpdated",DateTime.Now.ToShortDateString(), this);
                    return downloadedImage;
                }

                Current += interleave;

                if ((i.ToString("yyyyMMdd", us).Substring(0, 4) != year) ||
                    i.ToString("yyyyMMdd", us).Substring(4, 2) != month)
                {
                    year = i.ToString("yyyyMMdd", us).Substring(0, 4);
                    month = i.ToString("yyyyMMdd", us).Substring(4, 2);
                    string url = URL + "?m=" + month + "&y=" + year + "#";
                    webPage = Util.GetHtmlPage(url, Encoding.UTF8);
                }

                string strResults = webPage;
                string strParsing = "#" + i.ToString("yyyyMMdd", us) + "-us";

                int intTemp = strResults.IndexOf(strParsing);
                if (intTemp > -1)
                {
                    strResults = strResults.Substring(intTemp + strParsing.Length);
                    strParsing = @"resize.php?i=";
                    strResults = strResults.Substring(strResults.IndexOf(strParsing) + strParsing.Length);
                    strParsing = @"&";
                    string fileName = strResults.Substring(0, strResults.IndexOf(strParsing)).Trim();

                    if (Util.GetImage("http://www.istartedsomething.com/bingimages/cache/" + fileName,
                        string.Empty, this.GetType().Name, fileName,true) > 0)
                    {
                         downloadedImage++;
                         this.LastDwImage = i.ToString("yyyyMMdd", us);
                         Util.SaveToConfigFile("LastDwImage", i.ToString("yyyyMMdd", us), this);
                         CurrentImage = this.LastDwImage;
                         Images = Util.LoadImage(Utils.Providers.Bing, initPath);
                    }
                }               
            }
            this.LastUpdated = DateTime.Now;
            Util.SaveToConfigFile("LastUpdated", DateTime.Now.ToShortDateString(), this);
            return downloadedImage;
        }
        public int update()
        {
            DateTime start;
            CultureInfo us = CultureInfo.GetCultureInfo("en-US");

            if (DateTime.TryParseExact(LastDwImage, "yyyyMMdd", us, DateTimeStyles.None, out start) == true)
                return getImages(start);
            else if (DateTime.TryParseExact(FirstImage, "yyyyMMdd", us, DateTimeStyles.None, out start) == true)
                return getImages(start);
            else
                return 0;
        }
        public void CancelAsync()
        {
            this._isCancelationPending = true;
        }

    }
}
